package com.chenwc.rocketmq.example;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * 普通消息发送
 *
 * @author chenwc
 */
public class ProducerNormalMessageExample {
    private static final Logger logger = LoggerFactory.getLogger(ProducerNormalMessageExample.class);

    private ProducerNormalMessageExample() {
    }

    public static void main(String[] args) throws MQClientException {

        String topic = "TopicTest";
        final DefaultMQProducer producer = ProducerSingleton.getInstance(topic);

        // 定义消息体
        byte[] body = "This is a normal message for Apache RocketMQ".getBytes(StandardCharsets.UTF_8);
        // 定义消息标签
        String tag = "TagA";
        // 定义消息key
        String keys = UUID.randomUUID().toString().toUpperCase().replace("-", "");
        // 创建消息对象
        final Message message = new Message(topic, tag, keys, body);

        try {
            // 发送消息
            final SendResult sendResult = producer.send(message);
            logger.info("Send message successfully, {}", sendResult.toString());
        } catch (Throwable t) {
            logger.error("Failed to send message", t);
        }
        // 关闭生产者
        ProducerSingleton.closeInstance();
    }
}
